package org.ms.springboot.config;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@ToString
@Configuration /* @Configuration或@Component */
@ConfigurationProperties(prefix = "test.gateway.rate-limiter")
public class RateLimiterProperties {

    private boolean enabled = false;
    private int globalRate = 0;
    private Map<String, LimiterRule> rules = new HashMap<>();

    @Data
    @ToString
    public static class LimiterRule {
        private String[] urls = new String[0];
        private Integer rate = 0;
    }

    public Map<String[], Integer> convertRuleToMap() {
        Map<String[], Integer> ruleMap = new HashMap<>();
        rules.forEach((k, v) -> ruleMap.put(v.getUrls(), v.getRate()));
        return ruleMap;
    }

    public String[] allRulePath() {
        List<String> pathList = new ArrayList<>();
        rules.forEach((k, v) -> {
            for (String pattern : v.getUrls()) {
                pathList.add(pattern);
            }
        });
        return pathList.stream().toArray(String[]::new);
    }

    public List<LimiterRule> findRuleList() {
        List<LimiterRule> ruleList = new ArrayList<>();
        rules.forEach((k, v) -> ruleList.add(v));
        return ruleList;
    }

}